package com.file.csv.read;

import com.file.csv.pojo.CSV;
import com.file.txt.pojo.TxtUser;
import com.file.txt.utils.TransBeanUtils;
import com.opencsv.CSVParser;
import com.opencsv.CSVReader;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ReadCSV {

    public static <T> List<T>  readCsv(String path, Class<T> clazz) {
        List<T> beans = new ArrayList<>();
        try {
            DataInputStream in = new DataInputStream(new FileInputStream(new File(path)));
            // CSVReader csvReader = new CSVReader(new InputStreamReader(in,"GBK"));
            CSVReader csvReader = new CSVReader(
                    new InputStreamReader(in, "GBK"),
                    CSVParser.DEFAULT_SEPARATOR,
                    CSVParser.DEFAULT_QUOTE_CHARACTER,
                    CSVParser.DEFAULT_ESCAPE_CHARACTER,
                    1);
            String[] strs;

            while ((strs = csvReader.readNext()) != null) {
                String[] split = Arrays.deepToString(strs).split(",");
                T bean = TransBeanUtils.getMappingPo(clazz, split);
                beans.add(bean);
            }
            csvReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return beans;
    }
}
